import React from 'react';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Input, message, Button, Card, Checkbox, Select, InputNumber, Divider } from 'antd';
import { connect } from 'dva';
import PropTypes from 'prop-types';
import router from 'umi/router';
import * as R from 'ramda';

const transferOption = (arrayData = [], keyValue = ['value', 'label']) =>
  R.map(
    item => <Select.Option key={item[keyValue[0]]}>{item[keyValue[1]]}</Select.Option>,
    arrayData,
  );
const FormItem = Form.Item;
const { TextArea } = Input;
const formItemLayout = {
  labelCol: {
    xs: { span: 12 },
    sm: { span: 6 },
  },
  wrapperCol: {
    xs: { span: 4 },
    sm: { span: 14 },
  },
};
@Form.create()
@connect((state: any) => ({
  dataPackageConfig: state.dataPackageConfig,
  loading: state.loading.models['dataPackageConfig'],
  menu: state.menu,
}))
export default class DataPackageConfigAdd extends React.Component<any, any> {
  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      seriesOptions: [], // 车系列表
      nameOptions: [], //车型组列表
      codeOptions: [], // 套餐编码
      buttonLoading: false,
      brandOptions: [],
      brandId: '',
    };
  }

  static contextTypes = {
    permissions: PropTypes.array,
  };
  componentWillMount() {
    if (this.props.location && this.props.location.state) {
      this.setState({
        brandOptions:this.props.location.state.brandOption,
        brandId: this.props.location.state.brandId,
      });
    }
  }
  componentDidMount() {
    // 获取车系数据
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const brandId = this.props.location && this.props.location.state.brandId;
    dispatch({
      type: 'dataPackageConfig/getDataWithRes',
      payload: { url: '/msdevice/base/vehicle/series/bybrand/list', brandId },
      callback: (e: any) => {
        if (e.data) {
          this.setState({
            seriesOptions: e.data.map(e => ({
              seriesName: e.seriesName,
              seriesCode: e.seriesCode,
            })),
          });
        }
      },
    });
    // 获取套餐编码
    dispatch({
      type: 'dataPackageConfig/getDataWithRes',
      payload: { url: '/mno/package/code/list' },
      callback: (e: any) => {
        if (e.data) {
          this.setState({
            codeOptions: e.data.map(e => ({
              name: e.name,
              code: e.code,
            })),
          });
        }
      },
    });
  }
  onChange = (list: any) => {
    const { selectOptions } = this.state;
    console.log('选中的list', list);
    this.setState({
      checkedList: list,
      indeterminate: !!list.length && list.length < selectOptions.length,
      checkAll: list.length === selectOptions.length,
    });
  };
  onCheckAllChange = (e: any) => {
    console.log('checkAllCHangeE', e);
    console.log('是否全选', e.target.checked);
    const { selectOptions } = this.state;
    this.setState({
      checkedList: e.target.checked ? selectOptions : [],
      indeterminate: false,
      checkAll: e.target.checked,
    });
    const { form } = this.props;
    form.setFieldsValue({
      vehicleType: e.target.checked ? selectOptions : [],
    });
  };
  handleCancel = () => {
    if (this.props.location && this.props.location.state) {
      const { pageObj, formValues, backUrl } = this.props.location.state;
      router.push({ pathname: backUrl, state: { pageObj: pageObj, sourceRouter: 'dataPackage', formValues } });
    } else {
      router.push({ pathname: '/remoteConfiguration/dataPackageConfig'  , state: {sourceRouter: 'dataPackage'}});
    }
  };
  // 通过车系查询车型组信息
  onSelect = (value: any) => {
    if (value) {
      this.props.dispatch({
        type: 'dataPackageConfig/postData',
        payload: { url: '/vehicle/group/findBySeriesCode', seriesCode: value },
        callback: (e: any) => {
          if (e.data) {
            this.setState({
              nameOptions: e.data.map(e => ({
                name: e.name,
                groupCode: e.code,
              })),
            });
          } else {
            this.setState({
              nameOptions: '',
            });
          }
        },
      });
    } else {
      this.setState({
        nameOptions: '',
      });
    }
    // 重新选取车系，清空车型组所选内容
    const { form } = this.props;
    form.setFieldsValue({
      groupCode: '',
    });
  };
  handleOk = () => {
    const {
      dispatch,
      form: { validateFields },
    } = this.props;
    validateFields((err: any, values: any) => {
      if (err) {
        return;
      }
      this.setState({
        buttonLoading: true,
      });
      dispatch({
        type: 'dataPackageConfig/postObjWithRes',
        payload: { url: '/mno/package/new/batchSave', ...values },
        callback: (response: any) => {
          if (response.statusCode === '0') {
            message.success('操作成功！');
            this.handleCancel();
          } else {
            // message.error(response.statusMessage);
          }
          this.setState({ buttonLoading: false });
        },
      });
    });
  };
  checkFill = (rule, value, callback) => {
    const { form } = this.props;
    const activeUser = form.getFieldValue('activeUser');
    const activeInnerTest = form.getFieldValue('activeInnerTest');
    const activeShow = form.getFieldValue('activeShow');
    const activeTestDriver = form.getFieldValue('activeTestDriver');
    const activeMedia = form.getFieldValue('activeMedia');
    if (!(activeUser || activeInnerTest || activeShow || activeTestDriver || activeMedia)) {
      callback('请至少选择一项填写！');
      return;
    }
    callback();
  };
  render() {
    const { buttonLoading, seriesOptions, nameOptions, codeOptions } = this.state;
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <div>
        <Card bordered={false}>
          <Form layout="horizontal">
          <FormItem {...formItemLayout} label={<span>品牌&nbsp;</span>}>
              {getFieldDecorator('brandId', {
                 initialValue:this.state.brandId,
                 rules: [{ required: false, message: '请选择品牌' }],
              })(
                <Select placeholder="请选择" disabled={true}>
                  {transferOption(this.state.brandOptions, ['brandCode', 'brandName'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>车系&nbsp;</span>}>
              {getFieldDecorator('seriesCode', {
                rules: [{ required: true, message: '请选择车系' }],
              })(
                <Select placeholder="请选择" onChange={this.onSelect}>
                  {transferOption(seriesOptions, ['seriesCode', 'seriesName'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>车型组&nbsp;</span>}>
              {getFieldDecorator('groupCode', {
                rules: [{ required: true, message: '请选择车型组' }],
              })(
                <Select placeholder="请选择">
                  {transferOption(nameOptions, ['groupCode', 'name'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>服务年限&nbsp;</span>}>
              {getFieldDecorator('activeUserDuration', {
                rules: [{ required: true, message: '请输入服务年限' }],
              })(<InputNumber min={1} max ={100} placeholder="请输入服务年限" style={{ width: '25%' }} />)}
              <span className="ant-form-text">&nbsp;&nbsp;月</span>
            </FormItem>
            <FormItem
              {...formItemLayout}
              label={<span>激活类型&nbsp;</span>}
              //  noStyle
            >
              {getFieldDecorator('activeType', {
                rules: [{ required: true, validator: this.checkFill }],
              })(<div></div>)}
            </FormItem>
            <Divider />
            <FormItem {...formItemLayout} label={<span>用户&nbsp;</span>}>
              {getFieldDecorator('activeUser', {
                rules: [{ required: false, message: '请选择' }],
              })(
                <Select placeholder="请选择" allowClear>
                  {transferOption(codeOptions, ['code', 'name'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>内部测试&nbsp;</span>}>
              {getFieldDecorator('activeInnerTest', {
                rules: [{ required: false, message: '请选择' }],
              })(
                <Select placeholder="请选择" allowClear>
                  {transferOption(codeOptions, ['code', 'name'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>展车&nbsp;</span>}>
              {getFieldDecorator('activeShow', {
                rules: [{ required: false, message: '请选择' }],
              })(
                <Select placeholder="请选择" allowClear>
                  {transferOption(codeOptions, ['code', 'name'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>试乘试驾&nbsp;</span>}>
              {getFieldDecorator('activeTestDriver', {
                rules: [{ required: false, message: '请选择' }],
              })(
                <Select placeholder="请选择" allowClear>
                  {transferOption(codeOptions, ['code', 'name'])}
                </Select>,
              )}
            </FormItem>
            <FormItem {...formItemLayout} label={<span>媒体车&nbsp;</span>}>
              {getFieldDecorator('activeMedia', {
                rules: [{ required: false, message: '请选择' }],
              })(
                <Select placeholder="请选择" allowClear>
                  {transferOption(codeOptions, ['code', 'name'])}
                </Select>,
              )}
            </FormItem>
            <Divider />
            <FormItem {...formItemLayout} label={<span>备注&nbsp;</span>}>
              {getFieldDecorator('remark', {
                rules: [{ required: false, message: '请输入套餐备注' }],
              })(<TextArea placeholder="请输入套餐备注" rows={4} />)}
            </FormItem>
            <FormItem wrapperCol={{ offset: 8, span: 16 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={buttonLoading}
                onClick={this.handleOk}
              >
                {' '}
                保存{' '}
              </Button>
              <Button style={{ marginLeft: 10 }} onClick={this.handleCancel}>
                {' '}
                取消{' '}
              </Button>
            </FormItem>
          </Form>
        </Card>
      </div>
    );
  }
}
